<template>
  <div class="cascader-table-app">
    <!-- 应用头部 -->
    <AppHeader />
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 筛选器区域 -->
      <FilterSection
        v-model:selectedValue="selectedValue"
        :options="cascaderOptions"
        :loading="loading"
        @filter-change="handleFilterChange"
      />
      
      <!-- 数据表格区域 -->
      <DataTableSection
        :tableData="tableData"
        :loading="loading"
        :requestInfo="requestInfo"
        @refresh="refreshData"
      />
      
      <!-- 操作日志区域 -->
      <LogSection :logs="operationLogs" @clear-logs="clearLogs" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import AppHeader from './components/AppHeader.vue'
import FilterSection from './components/FilterSection.vue'
import DataTableSection from './components/DataTableSection.vue'
import LogSection from './components/LogSection.vue'
import type { 
  CascaderOption, 
  TableDataItem, 
  RequestInfo, 
  OperationLog,
  ApiResponse 
} from './types/app'
import { useCascaderData } from './composables/useCascaderData'
import { useTableData } from './composables/useTableData'
import { useOperationLog } from './composables/useOperationLog'

// 使用组合函数
const { cascaderOptions } = useCascaderData()
const { tableData, loading, fetchTableData } = useTableData()
const { operationLogs, addLog, clearLogs } = useOperationLog()

// 响应式数据
const selectedValue = ref<string[]>([])
const selectedLabels = ref<string[]>([])

// 计算属性 - 请求参数（最深层级的值）
const requestParam = computed<string>(() => {
  if (!selectedValue.value.length) return ''
  return selectedValue.value[selectedValue.value.length - 1]
})

// 计算属性 - 请求信息
const requestInfo = computed<RequestInfo>(() => ({
  url: '/api/table/data',
  method: 'POST',
  params: {
    category: requestParam.value || null,
    page: 1,
    pageSize: 20
  },
  status: loading.value ? 'loading' : 'success'
}))

// 方法 - 处理级联选择器变更
const handleFilterChange = (value: string[], selectedOptions: CascaderOption[]): void => {
  selectedLabels.value = selectedOptions.map(opt => opt.nameCn)
  
  const pathText = selectedLabels.value.join(' → ')
  addLog(`级联选择器变更: ${pathText}`)
  addLog(`提取请求参数: ${requestParam.value}`)
  
  // 自动触发数据请求
  if (requestParam.value) {
    loadTableData(requestParam.value)
  } else {
    tableData.value = []
    addLog('清空表格数据')
  }
}

// 方法 - 加载表格数据
const loadTableData = async (category: string): Promise<void> => {
  try {
    addLog(`开始请求表格数据: category=${category}`)
    const result = await fetchTableData(category)
    addLog(`请求成功，获取到 ${result.length} 条数据`)
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    addLog(`请求失败: ${errorMessage}`)
    console.error('加载表格数据失败:', error)
  }
}

// 方法 - 刷新数据
const refreshData = (): void => {
  if (requestParam.value) {
    addLog('手动刷新表格数据')
    loadTableData(requestParam.value)
  }
}

// 监听选中值变化
watch(selectedValue, (newValue: string[], oldValue: string[]) => {
  console.log('级联选择器值变化:', {
    old: oldValue,
    new: newValue,
    requestParam: requestParam.value
  })
}, { deep: true })

// 组件挂载时的初始化
onMounted(() => {
  addLog('应用初始化完成')
  console.log('CascaderTableApp mounted')
})
</script>

<style scoped>
.cascader-table-app {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }
}
</style>
